package com.xj.demo.gcdemo;

import java.util.ArrayList;
import java.util.List;

public class STWDemo {
    static List<Long> seconds = new ArrayList<>();
    static boolean printAvg = true;
    public static class Worker extends Thread {
        List<byte[]> list = new ArrayList<>();

        @Override
        public void run() {
            while (true) {
                for (int i = 0; i < 1000; i++) {
                    list.add(new byte[1024]);
                }
                if (list.size() > 10000) {
                    list.clear();
                    System.gc();
                }
            }
        }
    }

    public static class Printer extends Thread {
        static final long START_TIME = System.currentTimeMillis();

        public void run() {
            try{
                while (true) {
                    long l = System.currentTimeMillis();
                    long diff = l - START_TIME;
                    seconds.add(diff);
                    System.out.println(diff / 1000 + "." + diff % 1000);
                    Thread.sleep(1000);
                }
            }catch (InterruptedException e){
                e.printStackTrace();
            }

        }
    }

    public static void main(String[] args) {
        try {
            //Worker worker = new Worker();
            Printer printer = new Printer();
            //worker.start();
            printer.start();

            while (printer.isAlive()) {

                if (seconds.size() > 0) {
                    if (seconds.size() % 10 == 0) {
                        printAvg = true;
                    }
                }else {
                    printAvg = false;
                }
                while (printAvg) {
                    long sum = 0;
                    for (int i = 0; i < seconds.size() - 1; i++) {
                        sum += seconds.get(i + 1) - seconds.get(i);
                    }
                    System.out.println("count avg:" + sum / seconds.size());
                    printAvg = false;
                }
            }
        }finally {
            //对seconds元素求和

        }

    }
}
